package com.google.code.virtualhockey.vhx.server.service

import com.google.code.virtualhockey.vhx.server.servlet.VhxEnv
import com.google.appengine.api.users.{User, UserServiceFactory}

/**
 * Provides access to user related information.
 */
object UserService {

  private val _userService = UserServiceFactory.getUserService

  /**
   * Indicates whether the currently connected user is authenticated or not.
   */
  def isAuthenticated: Boolean = _userService.isUserLoggedIn

  /**
   * Indicates whether the currently connected user is an administrator or not.
   */
  def isAdmin: Boolean = _userService.isUserAdmin

  /**
   * Returns the currently connected GAE user if any.
   */
  def getGaeUser: Option[User] = {
    val user = _userService.getCurrentUser
    if ( user == null )
      return None
    else
      return Some( user )
  }

  /**
   * Returns the user's email address (the one that was used for login).
   */
  def getUserEmail = {
    val user = _userService.getCurrentUser
    if ( user == null )
      sys.error( "Connected user is not authenticated. Impossible to retrieve its name." )
    else
      user.getEmail
  }

  /**
   * Returns the URL to be used to redirect the connected user to the login page.
   */
  def getLoginUrl = _userService.createLoginURL( VhxEnv.HOST_PAGE_URL )

  /**
   * Returns the URL to be used to redirect the connected user to the login page.
   */
  def getLogoutUrl = _userService.createLogoutURL( VhxEnv.HOST_PAGE_URL )
}
